<?php

/**
 * Description of AdminController
 *
 * @author Poh Nean
 */
class AdminController extends PsController
{

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('Tickets.Manage'),
					)), parent::accessRules());
	}

	public function actionIndex($ticket_status = 'Open')
	{
		$ticket = new Ticket('searchByAgency');
		
		$ticket->unsetAttributes();
		//$ticket->current_status = $ticket_status;

		if (isset($_GET['Ticket'])) {
			$ticket->attributes = $_GET['Ticket'];
			$ticket->agency_id = Yii::app()->user->model->agency_id;
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['ticket_status'] = $ticket_status;
		//$data['ticketStatusTypes'] = TicketStatusType::model()->findAll(array('order' => 'is_closing_status ASC'));
		$this->render('index', $data);
	}

	public function actionView($ticket_code)
	{
		$ticket = $this->loadTicket($ticket_code);

		$newTicketResponse = new TicketResponse;

		if (isset($_POST['TicketResponse'])) {
			$newTicketResponse->ticket_id = $ticket->id;
			$newTicketResponse->user_id = Yii::app()->user->id;
			$newTicketResponse->agency_id = Yii::app()->user->model->agency_id;
			$newTicketResponse->update_time = new CDbExpression('UTC_TIMESTAMP()');
			$newTicketResponse->attributes = $_POST['TicketResponse'];

			if ($newTicketResponse->validate()) {
				$tx = Yii::app()->db->beginTransaction();
				try {
					if (isset($_POST['Ticket'])) {
							
							$Status = TicketStatusHistory::model()->findByAttributes(array('ticket_id'=>$ticket->id),array('order'=>'update_time ASC'));
							//dump($Status);exit;
							$oldType = $Status->ticket_status_type_id;
							//echo $oldType; exit;
						if ($_POST['alsoChangeStatus'] == 1) {
							//echo 'ddd';exit;
							$newType = $_POST['Ticket']['ticket_type_id'];
							//echo ($newType.'--'.$oldType);exit;
							if ($newType != $oldType) {
								$ticketStatus = new TicketStatusHistory;
								
								$ticketStatus->ticket_status_type_id = $newType;
								$ticketStatus->ticket_id = $ticket->id;
								$ticketStatus->update_time = new CDbExpression('UTC_TIMESTAMP()');
								$ticketStatus->change_by_user_id = Yii::app()->user->id;
								
								$ticketStatus->save(false);
							}

							$ticket->save(false);
						}
						//echo 'dfff';exit;
					}
					//echo 'dd';exit;
					if (!$newTicketResponse->validate()){
						dump($newTicketResponse->getErrors());
					}
					
					$newTicketResponse->save(false);
					
					//$ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_UPDATED, array('response' => $newTicketResponse->message));

					$tx->commit();

					$this->refresh();
				} catch (CDbException $e) {
					//$tx->rollback();
					
					exit('ddd');
				}
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		//$data['escalation'] = new Escalation;
		//$data['ticketEscalationLevels'] = $ticket->getEscalationLevelsListData();
		$data['newTicketResponse'] = $newTicketResponse;
		$this->render('view', $data);
	}

	public function actionAssign($ticket_code)
	{
		$ticket = $this->loadTicket($ticket_code);
	    $newUserHasTicket = new UserHasTicket;
        $newTicketTeamHasTicket = new TicketTeamHasTicket;
		if (isset($_POST['UserHasTicket'])||isset($_POST['TicketTeamHasTicket'])) {
		    $newUserHasTicket->ticket_id = $ticket->id;
			$newTicketTeamHasTicket->ticket_id = $ticket->id;
			$newUserHasTicket->attributes = $_POST['UserHasTicket'];
			$newTicketTeamHasTicket->attributes = $_POST['TicketTeamHasTicket'];
			if ($newUserHasTicket->validate()) {
				$tx = Yii::app()->db->beginTransaction();
				try {
					if (!$newUserHasTicket->validate()){
						dump($newUserHasTicket->getErrors());
					}		
					$newUserHasTicket->save(false);
					$tx->commit();
				} catch (CDbException $e) {
					exit('ddd');
				}
			}
			if ($newTicketTeamHasTicket->validate()) {
				$tx = Yii::app()->db->beginTransaction();
				try {
					if (!$newTicketTeamHasTicket->validate()){
						dump($newTicketTeamHasTicket->getErrors());
					}		
					$newTicketTeamHasTicket->save(false);
					$tx->commit();
				} catch (CDbException $e) {
					exit('ddd');
				}
			}
			$this->refresh();
		}

		$data = array();
		$data['ticket'] = $ticket;
		$data['newUserHasTicket'] = $newUserHasTicket;
		$data['newTicketTeamHasTicket'] = $newTicketTeamHasTicket;
		$this->render('assign', $data);
	}
	
	public function actionCreate()
	{
		$ticket = new Ticket;
		//dump ($ticket);exit;
		if (isset($_POST['Ticket'])) {
			$ticket->attributes = $_POST['Ticket'];
			$ticket->agency_id = Yii::app()->user->model->agency_id;
			
			$ticket->created_by_user_id = Yii::app()->user->id;
			
			$ticket->ticket_code = uniqid(time() . rand(10*45, 100*98));
			$ticket->ticket_client_id = time() . rand(10*45, 100*98);
			//dump ($ticket); exit; 
			$isValid = $ticket->validate();
			
			if ($isValid == false ) {
				dump ($ticket->getErrors()); exit; 
			}
			//echo '1';exit;
			if ($isValid) {
				
				//dump($ticket->save());exit;
				$tx = Yii::app()->db->beginTransaction();
				
				
				try {
					$ticket->save(false);
					$ticketStatus = new TicketStatusHistory;
					//dump($ticketStatus);exit;
					
					$ticketStatus->ticket_status_type_id = 1;
					$ticketStatus->ticket_id = $ticket->id;
					//$TicketStatusHistory->update_time = new CDbExpression('UTC_TIMESTAMP()');
					$ticketStatus->update_time = new CDbExpression('UTC_TIMESTAMP()');
					$ticketStatus->change_by_user_id = Yii::app()->user->id;
					//dump($ticketStatus);die('1231');
					$isValid2 = $ticketStatus->validate();
					if ($isValid2 == false ) {
						//dump ($ticketStatus->getErrors()); exit; 
					} 
					
					$ticketStatus->save(false);
					
					$ticketClient = new TicketClient;
					
					$ticketClient->email = $ticket->email;
					$ticketClient->ticket_code = $ticket->ticket_code;
					$ticketClient->save(false);
					
					$tx->commit();
					
					//$ticket->sendNotificationEmail(Ticket::NOTIFICATION_TYPE_NEW);
					// Send mail
					
					$mails = new MailHelper;
					$message = $mails->createTicket($ticket);
					$to = $ticket->email;
					$headers = "From: " . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'Reply-To:' . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'X-Mailer: PHP/' . phpversion();
					$headers .= 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
					mail( $to  , 'New Ticket', $message , $headers);
				
				
					$this->redirect(array('admin/index'));
					PsSystemMessage::add('Ticket submitted.', 'success');
				} catch (CDbException $e) {
					$tx->rollback();
				}
			} else {
//				dump($ticket->getErrors());
			}
		}

		$data = array();
		$data['ticket'] = $ticket;
		$this->render('create', $data);
	}

	public function actionUpdate($ticket_code)
	{
		$ticket = $this->loadTicket($ticket_code);
		$oldType = $ticket->ticket_type_id;

		if (isset($_POST['Ticket'])) {
			$ticket->attributes = $_POST['Ticket'];
			$isValid = $ticket->validate();

			if ($isValid) {
				$tx = Yii::app()->db->beginTransaction();

				try {
					if ($ticket->ticket_type_id != $oldType) {
						// record ticket history
						$ticketStatus = new TicketStatusHistory;
						
						$ticketStatus->ticket_status_type_id = $ticket->ticket_type_id;
						$ticketStatus->ticket_id = $ticket->id;
						//$TicketStatusHistory->update_time = new CDbExpression('UTC_TIMESTAMP()');
						$ticketStatus->update_time = new CDbExpression('UTC_TIMESTAMP()');
						$ticketStatus->change_by_user_id = Yii::app()->user->id;
					
						$ticketStatus->save(false);
					}
					$ticket->save(false);

					$tx->commit();
					
					$mails = new MailHelper;
					$message = $mails->updateTicket($ticket);
					$to = $ticket->email;
					$headers = "From: " . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'Reply-To:' . Yii::app()->params['notificationsEmail'] . "\r\n" .
							'X-Mailer: PHP/' . phpversion();
					$headers .= 'MIME-Version: 1.0' . "\r\n";
					$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
					mail( $to  , 'Update Ticket', $message , $headers);
					
					$this->redirect(array('admin/index'));
					PsSystemMessage::add('Ticket updated.', 'success');
				}catch (CDbException $e){
					$tx->rollback();
				}
			} else {
				dump($ticket->getErrors());exit;
			}
		}
		
		$data = array();
		$data['ticket'] = $ticket;
		$this->render('update', $data);
	}

	public function actionEscalate($ticket_code)
	{
		$ticket = $this->loadTicket($ticket_code);
		if (isset($_POST['Escalation'])) {
			$escalationLevel = $this->loadEscalationLevel($_POST['Escalation']['escalation_level']);
			
			
			$escalation = new Escalation;
			$escalation->attributes = $_POST['Escalation'];
			
			$escalation->ticket_id = $ticket->id;
			$escalation->escalation_time = new CDbExpression('UTC_TIMESTAMP()');
			$escalation->escalated_to_user_id = $escalationLevel->user_id;
			
			if ($escalation->save()) {
				PsSystemMessage::add('Ticket #' . $ticket->ticket_code . ' escalated (Level ' . $escalation->escalation_level . ')', 'success');
			} else {
				PsSystemMessage::add('Error escalating ticket #' . $ticket->ticket_code, 'error');
			}
			
			$this->redirect(array('admin/view', 'ticket_code' => $ticket_code));
		}
	}
    /*
	public function loadTicket($ticket_code)
	{
		$ticket = Ticket::model()->ownedByCurrentAgency()->findByAttributes(array('ticket_code' => $ticket_code));

		if ($ticket == null) {
			throw new PsPageNotFoundException();
		}

		return $ticket;
	}*/
	public function actionDynamicTemplate(){
		$getdata =  $_POST['selectTemplate'];
		//echo $getdata; exit();
		echo time();
	}
	public function actionAjaxupdate()
	{
		$act = $_GET['act'];
		//echo $act;exit;
		if($act=='doClose')
		{
			$autoIdAll = $_POST['autoId'];
			if(count($autoIdAll)>0)
			{
				foreach($autoIdAll as $autoId){
					$ticket = Ticket::model()->findByAttributes(array('ticket_code' => $autoId));
					$Status = TicketStatusHistory::model()->findByAttributes(array('ticket_id'=>$ticket->id),array('order'=>'update_time DESC'));
					//dump($Status);exit;
					if ($Status->ticket_status_type_id == 1){
					
						$ticketStatus = new TicketStatusHistory;
						
						$ticketStatus->ticket_status_type_id = 2;
						$ticketStatus->ticket_id = $ticket->id;
						//$TicketStatusHistory->update_time = new CDbExpression('UTC_TIMESTAMP()');
						$ticketStatus->update_time = new CDbExpression('UTC_TIMESTAMP()');
						$ticketStatus->change_by_user_id = Yii::app()->user->id;
						
						$ticketStatus->save(false);
					}
					
				}
			}
			/*$sortOrderAll = $_POST['priority']; 
			if(count($sortOrderAll)>0)
			{
				foreach($sortOrderAll as $menuId=>$priority)
				{
					$model=$this->loadModel($menuId);
					$model->priority = $priority;
					$model->save();
				}
			}*/
		}
		else
		{
			$autoIdAll = $_POST['autoId'];
			if(count($autoIdAll)>0)
			{
				foreach($autoIdAll as $autoId){
					$model=$this->loadTicket($autoId);
					if($act=='doDelete'){
						//$image=$model->image;
						try {
							$ticketId= $model->id;
							if ($model->delete()){
								$ticketResponse = TicketResponse::model()->findAllByAttributes(array('ticket_id'=>$ticketId));
								if (isset($ticketResponse)){
									foreach($ticketResponse as $key =>$value ){
										$value->delete();
									}
								}
								
								$ticketHistory = TicketStatusHistory::model()->findAllByAttributes(array('ticket_id'=>$ticketId));
								if (isset($ticketHistory)){
									foreach($ticketHistory as $key =>$value ){
										$value->delete();
									}
								}
							}
						}
						catch (CDbException $e){
							echo 'failed';exit;
						}
					}             
					if($model->save())
						echo 'ok';
					else
						throw new PsPageNotFoundException();
	 
				}
			}
		}
	}
	
	public function loadTicket($ticket_code){
		$ticket=Ticket::model()->findByAttributes(array('ticket_code'=>$ticket_code));
		if($ticket===null)
			throw new PsPageNotFoundException();
		return $ticket;
	}
	
	/**
	 * @param int $level
	 * @return EscalationLevel
	 * @throws PsPageNotFoundException
	 */
	public function loadEscalationLevel($level) {
		$escalationLevel = EscalationLevel::model()->ofCurrentAgency()->findByAttributes(array('level' => $level));
		
		if ($escalationLevel === null) {
			throw new PsPageNotFoundException;
		}
		
		return $escalationLevel;
	}
	
	
	
	public function actionDynamiccities()
	{
		//$data=Location::model()->findAll('parent_id=:parent_id', 
					//  array(':parent_id'=>(int) $_POST['country_id']));
		echo (int)$_POST['country_id'];
		/*
		$data=CHtml::listData($data,'id','name');
		foreach($data as $value=>$name)
		{
			echo CHtml::tag('option',
					   array('value'=>$value),CHtml::encode($name),true);
		}
		*/
	}
	public function actionTest(){
		
		$this->render('test');
				
	}
	public function actionTestmail(){
		//$Status = TicketStatusHistory::model()->findByAttributes(array('ticket_id'=>35),array('order'=>'id DESC'));
		//dump($Status);exit;
		
		
		$notificationName  = Yii::app()->params["notificationsName"];
		$notificationEmail = Yii::app()->params["notificationsEmail"];
		
		$mailer = new Mailer();
		$mailer->From = $notificationEmail;
		$mailer->FromName = $notificationName;
		$mailer->AddAddress('congkhuong1308@gmail.com');
		
		$mailer->Subject = 'Test mail';
		
		$tokens['agency_name'] = 'Agency Name: khuong';
		
		
		$mailer->createHTMLMail(Yii::getPathOfAlias('common') . "/templates/emails/tickets/html/" .'new'. ".tpl", $tokens);
		$mailer->createTEXTMail(Yii::getPathOfAlias('common') . "/templates/emails/tickets/text/" .'new'. ".tpl", $tokens);
		dump($mailer);
		
		if ($mailer->sendMail()) echo 'Ok';
	}
}
?>
